package com.example.vueserver.vueserver.service;

import com.example.vueserver.vueserver.bean.SysRole;
import com.example.vueserver.vueserver.bean.SysUser;
import com.example.vueserver.vueserver.bean.SysUserRole;
import com.example.vueserver.vueserver.dao.SysRoleMapper;
import com.example.vueserver.vueserver.dao.SysUserMapper;
import com.example.vueserver.vueserver.dao.SysUserRoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sysUserService")
public class SysUserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    public SysUser selectById(Integer id) {
        return userMapper.selectById(id);
    }

    public SysUser selectByName(String name) {
        return userMapper.selectByName(name);
    }

    public List<SysUser> list() {
        return userMapper.list();
    }

    public PageInfo listPage(int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex, pageSize).setOrderBy("id desc");
        PageInfo<SysUser> pageInfo = new PageInfo<>(this.userMapper.list());
        for (SysUser user : pageInfo.getList()) {
            user.setRoles(this.roleMapper.listUserRoles(user.getId()));
        }
        return pageInfo;
    }

    public Map saveOrUpdate(SysUser user) {
        Map resultMap = new HashMap();
        if(user.getId()==0){
            this.userMapper.save(user);
            for(SysRole role:user.getRoles()){
                this.userRoleMapper.saveSysUserRole(new SysUserRole(user.getId(),role.getId()));
            }
            resultMap.put("msg","保存成功");
            resultMap.put("msgCode",1);
        }else{
            Date date = new Date();
//            Format dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//            dateFormat.format(date);
            user.setModifiedTime(date);
            this.userMapper.update(user);
            this.userRoleMapper.deleteByUserId(user.getId());
            for(SysRole role:user.getRoles()){
                this.userRoleMapper.saveSysUserRole(new SysUserRole(user.getId(),role.getId()));
            }
            resultMap.put("msg","更新 成功");
            resultMap.put("msgCode",1);
        }
        return resultMap;
    }
}

